﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Coolzon.UI.DataPartLib
{
    static class TemplateInstanceCache
    {
        private static List<TemplateInstance> s_instanceList = new List<TemplateInstance>();

        /// <summary>
        /// 引用
        /// </summary>
        /// <returns></returns>
        public static TemplateInstance Reference(UI.Part refPart, Metadata.Part templateMetadata)
        {
            //for (int index = 0; index < s_instanceList.Count; index++)
            //{
            //    TemplateInstance instance = s_instanceList[index];
            //    if (instance.TemplateName == templateMetadata.Name
            //        && !instance.IsUsed)
            //    {
            //        instance.IsUsed = true;
            //        return instance;
            //    }
            //}

            // 创建新的
            UI.Part partInstance = PartFactory.CreatePart(templateMetadata.Type, string.Format("T{0}", Guid.NewGuid().ToString("N")));
            if (partInstance != null)
            {
                CPPEI.Coolzon.UI.Views.PartInstanceCache.BuildPart(partInstance, templateMetadata);
                partInstance.Init(refPart.PartContext);

                TemplateInstance templateInstance = new TemplateInstance();
                templateInstance.IsUsed = true;
                templateInstance.TemplateName = templateMetadata.Name;
                templateInstance.Instance = partInstance;
                //s_instanceList.Add(templateInstance);

                return templateInstance;
            }
            return null;
        }

        /// <summary>
        /// 回收
        /// </summary>
        /// <param name="instance"></param>
        public static void Recovery(Metadata.Part templateMetadata, Part instance)
        {
            //for (int index = 0; index < s_instanceList.Count; index++)
            //{
            //    TemplateInstance templateInstance = s_instanceList[index];
            //    if (templateInstance.TemplateName == templateMetadata.Name
            //        && templateInstance.Instance == instance)
            //    {
            //        templateInstance.IsUsed = false;
            //        return;
            //    }
            //}
        }
    }

    class TemplateInstance
    {
        [Obsolete("目前还获取不到这个值")]
        public string SceneName{get;set;}
        public string TemplateName{get;set;}
        public Part Instance{get;set;}

        /// <summary>
        /// 是否是被使用着
        /// </summary>
        public bool IsUsed = false;
    }
}
